package com.wn.interceptor;

import com.wn.common.enumeration.BusinessCode;
import com.wn.common.enumeration.MyAssert;
import com.wn.common.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 用户权限拦截器
 */
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;
    /**
     * 前置通知
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("访问资源：{}", request.getRequestURI());
        //判断是否是options请求，如果是则直接放行
        if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
            return true;
        }
        //获取请求头
        String token = request.getHeader("Authorization");
        //判断token是否存在
        MyAssert.error(Objects.isNull(token), BusinessCode.TOKEN_NOT_EXISTS);
        //验证token是否有效
        MyAssert.error(!jwtUtil.validateToken(token), BusinessCode.INVALID_TOKEN);
        //判断IP地址是否相同
        String ip = jwtUtil.getValue(token, "ip");
        String remoteAddr = jwtUtil.getRequestIP(request);
        MyAssert.error(!ip.equals(remoteAddr), BusinessCode.INVALID_IP);
        //放行
        return true;
    }
}